import java.io.*
import kotlin.text.StringBuilder

class CsvLoader(file: File) {

    private val input: InputStream

    init {
        input = FileInputStream(file)
    }

    private var lastIsCr = false
    private fun readLine(): String? {
        val buffer: MutableList<Byte> = mutableListOf()
        var byte: Int
        while (true) {
            byte = this.input.read()
            if (byte == -1)
                break
            else if (byte == '\n'.code) {
                if (lastIsCr) continue
                break
            }
            else if (byte == '\r'.code) {
                lastIsCr = true
                break
            }
            buffer.add(byte.toByte())
        }
        return if (buffer.size > 0)
            String(buffer.toByteArray())
        else
            null
    }

    var title: List<String>? = null
        get() {
            return if (field == null) {
                val line = this.readLine() ?: throw Error("Empty title line")
                field = line.split(',')
                field
            } else {
                field
            }
        }

        private set

    var row: List<String>? = null
        private set

    fun nextRow(): List<String>? {
        this.title
        val line = this.readLine()
        if (line == null) {
            this.row = null
        } else {
            var fieldValue = StringBuilder()
            val row = mutableListOf<String>()
            var mode = 0
            var lastIsQ = false

            var i = 0
            while (i < line.length) {
                val ch = line[i]
                if (mode == 0) {
                    // 外面
                    if (ch == ',') {
                        // 当前词结束
                        row.add(fieldValue.toString())
                        fieldValue = StringBuilder()
                    }
                    else if (ch == '"') {
                        mode = 1
                    }
                    else {
                        fieldValue.append(ch)
                    }
                }
                else if (mode == 1) {
                    // 引号中
                    if (ch == '"') {
                        if (line[i + 1] == '"') {
                            // 连续双引号
                            i += 1
                            fieldValue.append('"')
                        }
                        else {
                            // 退出双引号
                            mode = 0
                        }
                    }
                    else {
                        fieldValue.append(ch)
                    }
                }

                i += 1
            }

            // 最后一个词结束
            row.add(fieldValue.toString())
            this.row = row
        }
        return this.row
    }
}